const { checkout } = require('../routes');
const dbConfig = require('../utils/dbconfig');
const common = require('../utils/common')
var CryptoJS = require("crypto-js");
var request = require('request');
var querystring = require('querystring');

// 文件上传
const path=require('path');
const moment=require('moment')
const fs=require('fs');
const multer = require('multer')

// 指定图片存储位置
let uploadImg = multer({
	storage: multer.diskStorage({
		//设置文件存储位置
		destination: function(req, file, cb) {
			let dir = "./public/upload/Img/user";

			//判断目录是否存在，没有则创建
			if (!fs.existsSync(dir)) {
				fs.mkdirSync(dir, {
					recursive: true
				});
			}
			//dir就是上传文件存放的目录
			cb(null, dir);
		},
		//设置文件名称
		filename: function(req, file, cb) {
			let fileName =Date.now() + path.extname(file.originalname);
			//fileName就是上传文件的文件名
			cb(null, fileName);
		}
	})
});

// 账号密码登录
login = (req,res)=>{
  let username = req.body.userName,
      password = req.body.password;
  var sql = 'select * from user where userName=? and password=?';
  var sqlArr = [username,password];
  var callBack = (err,data)=>{
    if(err){
      console.log('连接出错');
    }else{
      if(data.length > 0){
        res.send({
          'code':200,
          'message':'用户信息正确',
          'data':data[0]
        });
      }else{
        res.send({
          'code':400,
          'message':'用户信息错误'
        });
      }
    }
  };
  dbConfig.sqlConnect(sql,sqlArr,callBack)
}

// 查看用户名是否被注册
checkUserName=(req,res) => {
  let username = req.query.username;
  let sql = 'select * from user where userName=?';
  let sqlArr = [username];
  let callBack = (err,data)=>{
    if(err){
      console.log('连接出错');
    }else{
      if(data.length > 0){
        res.send({
          'code':200,
          'message':'用户以被注册'
        });
      }else{
        res.send({
          'code':400,
          'message':'用户未被注册'
        });
      }
    }
  };
  dbConfig.sqlConnect(sql,sqlArr,callBack)
}

// 查看手机号码是否被注册
checkUserPhone=(req,res) => {
  let phoneNum = req.query.phoneNum;
  let sql = 'select * from user where userPhone=?';
  let sqlArr = [phoneNum];
  let callBack = (err,data)=>{
    if(err){
      console.log('连接出错');
    }else{
      if(data.length > 0){
        res.send({
          'code':200,
          'message':'用户以被注册'
        });
      }else{
        res.send({
          'code':400,
          'message':'用户未被注册'
        });
      }
    }
  };
  dbConfig.sqlConnect(sql,sqlArr,callBack)
}

// 用户注册 
register = (req,res) => {
  let params = req.body;
  let sql = 'insert into user(userName,password,userPhone,addDate,userexper,userImg) value(?,?,?,?,?,?)';
  let sqlArr = [params.username,params.password,params.phoneNum,params.addDate,1,'upload/Img/user/userPicture.jpeg'];
  let callBack = (err,data)=>{
    if(err){
      console.log(err);
    }else{
      if(data.affectedRows === 1){
        res.send({
          'code':200,
          'message':'注册成功'
        });
      }else{
        res.send({
          'code':400,
          'message':'注册失败'
        });
      }
    }
  };
  dbConfig.sqlConnect(sql,sqlArr,callBack)
}

// 发送验证码
sendMessageCode = (req,res)=>{
  let phoneNum = req.body.phoneNum;
  let code = common.rand(1000,9999)
  // 云市场分配的密钥Id
  var secretId = "AKIDHZKw1qd8a5a9X726vvFi8yDNGLSNU0tE2uWN";
  // 云市场分配的密钥Key
  var secretKey = "D1i8zYHpsc3DygcTYIbeXP6c55n4k82N2b8wi3f";
  var source = "market";
  
 // 签名
  var datetime = (new Date()).toGMTString();
  var signStr = "x-date: " + datetime + "\n" + "x-source: " + source;
  var sign = CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA1(signStr, secretKey))
  var auth = 'hmac id="' + secretId + '", algorithm="hmac-sha1", headers="x-date x-source", signature="' + sign + '"';
  
  // 请求方法
  var method = 'POST';
  // 请求头
  var headers = {
      "X-Source": source,
      "X-Date": datetime,
      "Authorization": auth,
  }
  // 查询参数
  var queryParams = {
  }
  // body参数（POST方法下）
  var bodyParams = {
      'content': 'code:'+code,
      'phone_number': phoneNum,
      'template_id': 'TPL_0000'}
  // url参数拼接
  var url = 'https://service-6pdvpyfd-1300075552.bj.apigw.tencentcs.com/release/data/send_sms';
  if (Object.keys(queryParams).length > 0) {
      url += '?' + querystring.stringify(queryParams);
  }
  
  var options = {
      url: url,
      timeout: 5000,
      method: method,
      headers: headers
  }
  if (['POST', 'PUT', 'PATCH'].indexOf(method) != -1) {
      options['body'] = querystring.stringify(bodyParams);
      options['headers']['Content-Type'] = "application/x-www-form-urlencoded";
  }
  
  request(options, function (error, response, body) {
      if (error !== null) {
          console.log('error:', error);
          res.send({
            'code':400,
          })
          return;
      }
      let message = {
        'phone':phoneNum,
        'code':code
      }
      res.send({
        'code':200,
        'data': message
      })
  });
}

// 得到用户信息by电话
getInfoByPhone = (req,res)=>{
  let sql = 'select * from user where userPhone=?';
  let sqlArr = [req.body.userPhone];
  let callBack = (err,data)=>{
    if(err){
      console.log('连接出错');
    }else{
      if(data.length > 0){
        res.send({
          'code':200,
          'data':data[0]
        });
      }else{
        res.send({
          'code':400,
        });
      }
    }
  };
  dbConfig.sqlConnect(sql,sqlArr,callBack)
}

// 上传用户头像
uploadUserImg = (req,res)=>{
	let url=`upload/Img/user/`+req.files[0].filename; //之后用于存储在数据库的路径
	//将图片地址返回前端
	res.json({ok: true,url: url})
}

// 更新用户头像
updateUserImg = (req,res)=>{
  let userId = req.body.id,
      userImg = req.body.userImg;
  var sql = 'UPDATE user SET userImg=? WHERE uid=?';
  var sqlArr = [userImg,userId];
  var callBack = (err,data)=>{
    if(err){
      console.log('连接出错');
    }else{
      if(data.affectedRows === 1){
        res.send({
          'code':200,
          'message':'修改成功'
        });
      }else{
        res.send({
          'code':400,
          'message':'修改失败'
        });
      }
    }
  };
  dbConfig.sqlConnect(sql,sqlArr,callBack)
}

// 更新用户信息
updateUserInfo = (req,res)=>{
  let param = req.body;
  var sql = 'UPDATE user SET userName=?,`password`=?,userPhone=? WHERE uid=?';
  var sqlArr = [param.username,param.password,param.userphone,param.uid];
  var callBack = (err,data)=>{
  if(err){
    console.log('连接出错');
  }else{
    if(data.affectedRows === 1){
      res.send({
        'code':200,
        'message':'修改成功'
      });
    }else{
      res.send({
        'code':400,
        'message':'修改失败'
      });
    }
  }
  };
  dbConfig.sqlConnect(sql,sqlArr,callBack)
}
module.exports = {
  login,
  checkUserName,
  register,
  checkUserPhone,
  sendMessageCode,
  getInfoByPhone,
  uploadUserImg,
  uploadImg,
  updateUserImg,
  updateUserInfo
}